//
//  AppDelegate.m
//  XINNingOA
//
//  Created by 葛承铭 on 2021/7/11.
//

#import "AppDelegate.h"
#import "XNLoginViewController.h"
#import "XNMainViewController.h"
#import "YTKNetworkConfig.h"
#import "YTKNetworkAgent.h"
#import "XNBaseNavigationViewController.h"
#import "XNBaseBillInfoViewController.h"
#import "XNUtil.h"
#import "SVProgressHUD.h"

#import "JPUSHService.h"
// iOS10 注册 APNs 所需头文件
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif


@interface AppDelegate ()<JPUSHRegisterDelegate>

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    
    [SVProgressHUD setDefaultAnimationType:SVProgressHUDAnimationTypeNative];
    //强制更新
//    [XNUtil checkVersion];
    
    //正式环境
    [YTKNetworkConfig sharedConfig].baseUrl = @"http://47.103.59.143:8707";
    
    //测试环境
//    [YTKNetworkConfig sharedConfig].baseUrl = @"http://47.103.59.143:8780";
    YTKNetworkAgent *agent = [YTKNetworkAgent sharedAgent];
            NSSet *acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/plain", @"text/html", @"text/css", nil];
            NSString *keypath = @"jsonResponseSerializer.acceptableContentTypes";
            @try {
                [agent setValue:acceptableContentTypes forKeyPath:keypath];
            } @catch (NSException *exception) {
                NSLog(@"%@", exception);
            } @finally {

            }
    
    JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
    entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound;
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {

    }
    [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
    
    
    [JPUSHService setupWithOption:launchOptions
                           appKey:@"3af7ad26e75526650de225cf"
                          channel:@"App Store"
                 apsForProduction:YES
            advertisingIdentifier:nil];
    
    [JPUSHService registrationIDCompletionHandler:^(int resCode, NSString *registrationID) {
        if (resCode == 0) {
            NSLog(@"registrationID获取成功：%@", registrationID);
        } else {
            NSLog(@"registrationID获取失败，code：%d", resCode);
        }
    }];
    
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.backgroundColor = [UIColor whiteColor];
    NSString *account = [[NSUserDefaults standardUserDefaults] objectForKey:@"account"];
    if (account.length > 0) {
        XNBaseNavigationViewController *nav = [[XNBaseNavigationViewController alloc] initWithRootViewController:[[XNMainViewController alloc] init]];
        self.window.rootViewController = nav;
    }else{
        self.window.rootViewController = [[XNLoginViewController alloc] init];
    }
    [self.window makeKeyAndVisible];
    return YES;
    
    
}




- (void)applicationWillResignActive:(UIApplication *)application {
    [JPUSHService setBadge:0];
    [application setApplicationIconBadgeNumber:0];
    [application cancelAllLocalNotifications];
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    [JPUSHService setBadge:0];
    [application setApplicationIconBadgeNumber:0];
    [application cancelAllLocalNotifications];
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    [JPUSHService setBadge:0];
    [application setApplicationIconBadgeNumber:0];
    [application cancelAllLocalNotifications];
}



- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {

  /// Required - 注册 DeviceToken
  [JPUSHService registerDeviceToken:deviceToken];
}


- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
  //Optional
  NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}

#pragma mark- JPUSHRegisterDelegate

// iOS 12 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center openSettingsForNotification:(UNNotification *)notification{
  if (notification && [notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
    //从通知界面直接进入应用
  }else{
    //从通知设置界面进入应用
  }
}

// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
  // Required
  NSDictionary * userInfo = notification.request.content.userInfo;
  if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
    [JPUSHService handleRemoteNotification:userInfo];
  }
  completionHandler(UNNotificationPresentationOptionAlert); // 需要执行这个方法，选择是否提醒用户，有 Badge、Sound、Alert 三种类型可以选择设置
}

// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
  // Required
  NSDictionary * userInfo = response.notification.request.content.userInfo;
  if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
    [JPUSHService handleRemoteNotification:userInfo];
  }
    NSString *billCode = userInfo[@"BillCode"];
    NSString *orderId = userInfo[@"OrderId"];
    NSString *billName = userInfo[@"BillName"];
    UIViewController *vc = [UIApplication sharedApplication].keyWindow.rootViewController;
    if ([vc isKindOfClass:[UINavigationController class]]) {
        UINavigationController *nav = (UINavigationController *)[UIApplication sharedApplication].keyWindow.rootViewController;
        [nav popToRootViewControllerAnimated:YES];
        XNMainViewController *rootVC = nav.viewControllers.firstObject;
        rootVC.selectBillCode = billCode;

        XNBaseBillInfoViewController *jumpVC = [XNUtil getControllerWithOrderId:orderId];
        jumpVC.title = billName;
        [nav pushViewController:jumpVC animated:YES];

    }
    
    
    
  completionHandler();  // 系统要求执行这个方法
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {

  // Required, iOS 7 Support
  [JPUSHService handleRemoteNotification:userInfo];
  completionHandler(UIBackgroundFetchResultNewData);
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {

  // Required, For systems with less than or equal to iOS 6
  [JPUSHService handleRemoteNotification:userInfo];
}



@end
